const parseConfig = require('../../../config').parse
const menus = require('./_initConfig')
const Parse = require('parse/node')
Parse.initialize(parseConfig.appId, '', parseConfig.masterKey)
Parse.serverURL = parseConfig.serverURL
try {
  (async () => {
    let index = 0
    const parseMenus = menus.reduce((prev, cur) => {
      index++
      const name = cur.text
      const path = cur.route && cur.route.path
      const subMenus = cur.subMenu
      const role = cur.permission
      console.log(role)
      const Menu = Parse.Object.extend('Menu')
      const menuACL = new Parse.ACL()
      menuACL.setPublicReadAccess(false)
      menuACL.setPublicWriteAccess(false)
      menuACL.setRoleReadAccess('Admin', true)
      menuACL.setRoleWriteAccess('Admin', true)
      if (role) {
        menuACL.setRoleReadAccess(role, true)
      }
      const parent = new Menu({
        name,
        path,
        seq: index,
        icon: null,
        parent: null
      })
      parent.setACL(menuACL)
      prev.push(parent)
      prev.push(...subMenus.map((item, _index) => {
        const subName = item.text
        const path = item.route.path
        const subMenu = new Menu({
          parent,
          name: subName,
          path: path,
          seq: _index + 1,
          icon: null
        })
        subMenu.setACL(menuACL)
        return subMenu
      }))
      return prev
    }, [])

    Parse.Object.saveAll(parseMenus, {useMasterKey: true}).then(console.log).catch(console.log)
  })()
} catch (err) {
  console.log(err)
}

